<?php
/*
 * @ https://EasyToYou.eu - IonCube v11 Decoder Online
 * @ PHP 7.2 & 7.3
 * @ Decoder version: 1.1.6
 * @ Release: 10/08/2022
 */

// Decoded file for php version 71.
namespace longbingcore\wxcore;
use think\facade\Env;

class WxSetting
{
    protected $access_token;
    protected $appid;
    protected $appsecret;
    protected $uniacid = "7777";
    protected $config = [];

    public function __construct($uniacid = "666")
    {
        $this->uniacid = $uniacid;
        $this->config = $this->getConfig($this->uniacid);
        $this->appid = $this->getAppid();
        $this->appsecret = $this->getAppsecret();
    }

    public function getConfig($uniacid)
    {
        $config = longbingGetAppConfig($uniacid);
        return $config;
    }

    protected function getAppid()
    {
        if (isset($this->config["appid"])) {
            return $this->config["appid"];
        }
        return NULL;
    }

    protected function getAppsecret()
    {
        if (isset($this->config["appsecret"])) {
            return $this->config["appsecret"];
        }
        return NULL;
    }

    public function addTmpl($data)
    {
        $access_token = $this->lbSingleGetAccessToken();
        $url = "https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate?access_token=" . $access_token;
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        $res = $this->curlPost($url, $data);
        return $res;
    }

    public function lbSingleGetAccessToken()
    {
        $key = "longbing_card_access_token";
        $value = getCache($key, $this->uniacid);
        if ($value) {
            return $value;
        }
        $uniacid = $this->uniacid;
        if (!$this->checkConfig()) {
            return false;
        }
        $appid = $this->appid;
        $appsecret = $this->appsecret;
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
        $accessToken = file_get_contents($url);
        if (strstr($accessToken, "errcode")) {
            return 0;
        }
        $accessToken = json_decode($accessToken, true);
        $accessToken = $accessToken["access_token"];
        setCache($key, $accessToken, 7000, $uniacid);
        return $accessToken;
    }

    public function checkConfig()
    {
        $result = true;
        if (empty($this->uniacid) || empty($this->appid) || empty($this->appsecret)) {
            $result = false;
        }
        return $result;
    }

    public function curlPost($url, $post = NULL, $post_type = "POST")
    {
        $result = $this->crulGetData($url, $post, $post_type);
        return $result;
    }

    public function crulGetData($url, $post, $method, $header = 1)
    {
        $this->_errno = NULL;
        $this->_error = NULL;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        if ($post != NULL) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        if (Env::get("weixin.proxy_http_host")){
            curl_setopt($ch, CURLOPT_PROXY, Env::get("weixin.proxy_http_host"));
            curl_setopt($ch, CURLOPT_PROXYUSERPWD, Env::get("weixin.proxy_http_auth"));
        }

// 执行 cURL 会话并获取结果
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        if ($header) {
            curl_setopt($ch, CURLOPT_HEADER, false);
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json; charset=utf-8"]);
        $result = curl_exec($ch);
//        var_dump($result);
        $errno = curl_errno($ch);
        if (0 !== $errno){
            throw new \Exception("curl_exec error: " . curl_error($ch));
        }
//        var_dump($errno);
//        var_dump(curl_error($ch));
        return $result;
    }

    public function getAllTpmlList()
    {
        $access_token = $this->lbSingleGetAccessToken();
        $url = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=" . $access_token;
        $res = $this->curlPost($url, NULL, "GET");
        return $res;
    }

    public function deleteTmpl($tpml_id)
    {
        $access_token = $this->lbSingleGetAccessToken();
        $url = "https://api.weixin.qq.com/wxaapi/newtmpl/deltemplate?access_token=" . $access_token;
        $data["priTmplId"] = $tpml_id;
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        $res = $this->curlPost($url, $data);
        return $res;
    }

    public function sendTmpl($data)
    {
        $access_token = $this->lbSingleGetAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $access_token;
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        $res = $this->curlPost($url, $data);
        return $res;
    }

    public function getUserTmpl()
    {
        $access_token = $this->lbSingleGetAccessToken();
        $url = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=" . $access_token;
        $res = $this->curlPost($url, [], "GET");
        return $res;
    }

    public function sendCompanyMsg(array $data)
    {
        if (is_array($data)) {
            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        }
        $accessTokenWW = $this->companyMsgToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" . $accessTokenWW;
        $res = $this->curlPost($url, $data);
        return $res;
    }

    public function companyMsgToken()
    {
        $key = "longbing_card_access_token_qy_cn";
        $value = getCache($key, $this->uniacid);
        if ($value !== false) {
            return $value;
        }
        $send_model = new \app\sendmsg\model\SendConfig();
        $config = $send_model->configInfo(["uniacid" => $this->uniacid]);
        if (!empty($config["yq_corpid"]) && !empty($config["yq_corpsecret"])) {
            $key = $config["yq_corpid"];
            $secret = $config["yq_corpsecret"];
            $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" . $key . "&corpsecret=" . $secret;
            $accessToken = file_get_contents($url);
            $accessToken = json_decode($accessToken, true);
            if ($accessToken["errcode"] != 0) {
                echo json_encode(["code" => 402, "error" => "获取token失败"]);
                exit;
            }
            $accessToken = $accessToken["access_token"];
            setCache($key, $accessToken, 7200, $this->uniacid);
        }
        return !empty($accessToken) ? $accessToken : "";
    }

    public function qrCode($uid)
    {
        $accesstoken = $this->getGzhToken();
        $u = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $accesstoken;
        $param = [];
        $param["action_name"] = "QR_LIMIT_STR_SCENE";
        $param["action_info"] = ["scene" => ["scene_str" => $uid]];
        $param = json_encode($param);
        $res = $this->curlPost($u, $param, "post");
        $res = json_decode($res, true);
        $qrcode = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . $res["ticket"];
        $path = MATER_UPLOAD_PATH . date("Y-m-d", time()) . "/img";
        if (!is_dir($path)) {
            mkdir($path, 511, true);
        }
        $imageName = "/25220_" . date("His", time()) . "_" . rand(1111, 9999) . ".jpg";
        file_put_contents($path . $imageName, file_get_contents($qrcode));
        $qrcode = str_replace(FILE_UPLOAD_PATH, HTTPS_PATH, $path . $imageName);
        return $qrcode;
    }

    public function getGzhToken($update = 0)
    {
        $uniacid = $this->uniacid;
        $config = longbingGetAppConfig($this->uniacid);
        $appid = $config["web_app_id"];
        $gzh_secret = $config["web_app_secret"];
        $key = "articleToken-";
        $value = getCache($key, $uniacid);
        if ($value && $update == 0) {
            return $value;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $gzh_secret;
        $js_token = $this->crulGetData($url,false,'GET');
        $js_token = json_decode($js_token, true);
        if (isset($js_token["access_token"])) {
            $js_token = $js_token["access_token"];
            setCache($key, $js_token, 1200, $uniacid);
            return $js_token;
        }
        $str = "请求ac错误" . isset($js_token["errmsg"]) ? $js_token["errmsg"] : "";
        echo $str;
        exit;
    }

    public function batchChannelWechatQr($num)
    {
        $accesstoken = $this->getGzhToken();
        $qrcode = [];
        for ($i = 0; $i < $num; $i++) {
            $code = longbingorderCode() . $i;
            $u = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $accesstoken;
            $param = [];
            $param["action_name"] = "QR_LIMIT_STR_SCENE";
            $param["action_info"] = ["scene" => ["scene_str" => $code . "_chaqr"]];
            $param = json_encode($param);
            $res = $this->curlPost($u, $param, "post");
            $res = json_decode($res, true);
            if (!empty($res["ticket"])) {
                $qrcode[$i]["code"] = $code;
                $qrcode[$i]["qr"] = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . $res["ticket"];
            }
        }
        return $qrcode;
    }

    public function imgSecCheck($img_path)
    {
        $access_token = $this->lbSingleGetAccessToken();
        $url = "https://api.weixin.qq.com/wxa/img_sec_check?access_token=" . $access_token;
        $post_data = ["media" => new \CURLFile($img_path)];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 100);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function getWebTicket()
    {
        $config = longbingGetAppConfig($this->uniacid);
        $appid = $config["web_app_id"];
        $key = "ticket" . $appid;
        $ticket = getCacheAll($key, $this->uniacid);
        if ($ticket) {
            return $ticket;
        }
        $token = $this->getGzhToken(1);
        $ticket = $this->getArticleJsapiTicket($token);
//        var_dump($ticket);
        if (!empty($ticket)) {
            setCacheAll($key, $ticket, 3600, $this->uniacid);
        } else {
            clearCache($this->uniacid);
        }
        return $ticket;
    }

    public function getArticleJsapiTicket($js_token)
    {
        $ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $js_token . "&type=jsapi";
        $ticket_arr = @file_get_contents($ticket_url);
        $ticket_arr = @json_decode($ticket_arr, true);
        if (isset($ticket_arr["errcode"]) && $ticket_arr["errcode"] != 0) {
            return false;
        }
        $jsapi_ticket = $ticket_arr["ticket"];
        return $jsapi_ticket;
    }

    public function phpQrCode($data)
    {
        require_once EXTEND_PATH . "phpqrcode/phpqrcode.php";
        $errorCorrectionLevel = "L";
        $matrixPointSize = 10;
//        var_dump($data);
//        var_dump(12312);
//        exit;
        ob_start();
        \QRcode::png($data, false, $errorCorrectionLevel, $matrixPointSize, 2, false, 16777215, 0);
        $imgstr = base64_encode(ob_get_contents());
        ob_end_clean();
        $imgstr = "data:image/png;base64," . $imgstr;
        return $imgstr;
    }

    public function setH5Info()
    {
        $p = new \app\massage\info\PermissionMassage($this->uniacid);
        $value = $p->getSaasValue();
        if (is_numeric($value) && 0 < $value) {
            $config = $this->getConfig($this->uniacid);
            $app_id = $config["web_app_id"];
            $map = $config["map_secret"];
            $url = "https://" . $_SERVER["HTTP_HOST"] . "/index.php";
            $fileName = "siteinfo.json";
            $tempStr = "                let siteInfo = {\n                    \"uniacid\": \"666\",\n                    \"multiid\": \"0\",\n                    \"version\": \"3.0\",\n                    \"gzh_appid\": \"" . $app_id . "\",\n                    \"siteroot\": \"" . $url . "\",\n                    \"qqMapKey\":\"" . $map . "\"\n                    \n                }\n";
            \longbingcore\tools\LongbingFile::createDir(H5_PATH);
            defined("COACH_PATH") || define("COACH_PATH", $_SERVER["DOCUMENT_ROOT"] . "/coach/h5" . DS);
            \longbingcore\tools\LongbingFile::createDir(COACH_PATH);
            file_put_contents(H5_PATH . $fileName, $tempStr);
            file_put_contents(COACH_PATH . $fileName, $tempStr);
        }
        return true;
    }

    public function checkContent($content)
    {
        $access_token = $this->getGzhToken(1);
        $url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" . $access_token;
        $data = ["content" => $content];
        $res = lbCurlPost($url, urldecode(json_encode($data, JSON_UNESCAPED_UNICODE)));
        return $res;
    }

    public function checkKeyWordsv2($content)
    {
        $access_token = $this->lbSingleGetAccessToken();
        if (empty($access_token)) {
            return false;
        }
        $url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" . $access_token;
        $tmp = ["url" => $url, "data" => ["content" => urlencode($content)]];
        $rest = $this->curlPost($tmp["url"], urldecode(json_encode($tmp["data"])));
        $rest = json_decode($rest, true);
        $res = $rest["errcode"] == 0 ? true : false;
        return $res;
    }

    public function checkKeyWords($content)
    {
        $file_path = ROOT_PATH . "public/pub_sms_banned_words.txt";
        if (file_exists($file_path)) {
            $fp = fopen($file_path, "r");
            while (!feof($fp)) {
                $str_line = base64_decode(fgets($fp));
                $str_line = trim($str_line);
                if (false !== strstr($content, $str_line)) {
                    return false;
                }
            }
            fclose($fp);
        }
        return true;
    }

    public function getTmplList($uniacid)
    {
        $access_token = longbingGetAccessToken($uniacid);
        $url = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=" . $access_token;
        $a = file_get_contents($url);
        dump($a);
        exit;
    }
}

?>